<?php
require_once 'vendor/autoload.php';
use Phpml\Classification\KNearestNeighbors;
use Phpml\Association\Apriori;
use Phpml\Regression\LeastSquares;
use Phpml\Math\Statistic\StandardDeviation;
use Phpml\Math\Statistic\Correlation;
use Phpml\Dataset\CsvDataset;
use Phpml\Classification\Ensemble\RandomForest;

echo "<pre>";

/**K近邻算法**/
//应用于 文本分类、聚类分析、预测分析、模式识别、图像处理
$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);
$res = $classifier->predict([[4, 0]]);
// print_r($res);
// return b a


/**先验算法**/
//根据数据列出样本，和提供的一个样本，算出含有提供的样本的所有数据（以数组形式返回）
$samples = [['啤酒', '花生', '可乐'], ['啤酒', '花生', '奶糖'], ['啤酒', '花生', '可乐'], ['啤酒', '花生', '奶糖']];
$labels  = [];
$associator = new Apriori($support = 0.5, $confidence = 0.5);
$associator->train($samples, $labels);
$res = $associator->predict(['啤酒','奶糖']);

// print_r($res);
// return [['花生']]

$res = $associator->predict([['啤酒','可乐'],['花生','奶糖']]);
// print_r($res);
// return [[['花生']], [['啤酒']]]

//获取生成的关联规则只需使用rules方法。
$res = $associator->getRules();
// print_r($res);
// return [['antecedent' => ['啤酒', '奶糖'], 'consequent' => ['花生'], 'support' => 1.0, 'confidence' => 1.0], ... ]

//生成k长度的频繁项集只需使用apriori方法即可。
$res = $associator->apriori();
// print_r($res);
// return [ 1 => [['啤酒'], ['花生'], ['奶糖'], ['可乐']], 2 => [...], ...]


/**多元线性回归**/
$samples = [[73676, 1996], [77006, 1998], [10565, 2000], [146088, 1995], [15000, 2001], [65940, 2000], [9300, 2000], [93739, 1996], [153260, 1994], [17764, 2002], [57000, 1998], [15000, 2000]];//【里程 年份】
$targets = [2000, 2750, 15500, 960, 4400, 8800, 7100, 2550, 1025, 5900, 4600, 4400]; //价格
$regression = new LeastSquares();
$regression->train($samples, $targets);
$res = $regression->predict([60000, 1996]); //计算出 1996 年，60000里程的车，预测价格 是  4094.82
// print_r($res);
//return 4094.82

/**计算标准差**/
$population = [5, 6, 8, 9];
$res = StandardDeviation::population($population);
// print_r($res);
// return 1.825
$population = [7100, 15500, 4400, 4400, 5900, 4600, 8800, 2000, 2750, 2550,  960, 1025];
$res = StandardDeviation::population($population);
//print_r($res);
//return 4079

/**皮尔逊相关**/
$x = [144,830,22,243,580,96];
$y = [503,872,351,515,485,851];
$res = Correlation::pearson($x, $y);
// print_r($res);
//return 0.549


?>